package com._51cto.healthy.controller;

import com._51cto.healthy.content.R;
import com._51cto.healthy.pojo.Member;
import com._51cto.healthy.service.MemberService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;

@Controller
@RequestMapping("/member")
public class MemberController {
    @DubboReference
    MemberService memberService;


    @PostMapping("/login")
    @ResponseBody
    public R login(@RequestBody Member member) {
        Member loginUser = memberService.clientLogin(member.getPhoneNumber(), member.getPassword());
        if (loginUser == null) {
            return R.fail("账号或者密码错误");
        }
        return R.success(loginUser, "登录成功");
    }


    @PostMapping("/register")
    @ResponseBody
    public R register(@RequestBody Member member) throws ParseException {
        Member existUser = memberService.findUserByName(member.getPhoneNumber());
        if (existUser == null) {
            int i = memberService.clientRegister(member);
            if (i > 0) {
                return R.success("注册成功");
            } else {
                return R.fail("注册失败");
            }
        } else {
            return R.fail("该手机号已注册！！");
        }

    }

    @GetMapping("/{id}")
    @ResponseBody
    public R findById(@PathVariable Integer id) {
        Member member = null;
        boolean b = false;
        while (!b) {
            try {
                member = memberService.findUserById(id);
                b = true;
            } catch (RuntimeException e) {
                b = false;
            }
        }
        return R.success(member, "加载成功");
    }

    @PutMapping
    @ResponseBody
    public R updateMemberById(@RequestBody Member member) throws ParseException {
        int i = memberService.updateMemberById(member);
        return R.success(member, "修改成功");
    }
}
